package com.zhiwen.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhiwen.common.api.Result;
import com.zhiwen.domain.entity.Question;
import com.zhiwen.domain.entity.User;
import com.zhiwen.service.AiSearchService;
import com.zhiwen.service.SearchService;
import com.zhiwen.domain.vo.QuestionVO;
import com.zhiwen.domain.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 搜索控制器
 */
@RestController
@RequestMapping("/search")
@RequiredArgsConstructor
@Tag(name = "搜索接口", description = "提供搜索相关的功能接口")
public class SearchController {

    private final SearchService searchService;
    private final AiSearchService aiSearchService;

    /**
     * AI智能搜索问题
     */
    @GetMapping("/ai/questions")
    @Operation(summary = "AI智能搜索问题", description = "使用DeepSeek AI智能搜索相关问题")
    public Result<List<Map<String, Object>>> aiSearchQuestions(
            @Parameter(description = "搜索查询语句") @RequestParam String query,
            @Parameter(description = "返回结果数量") @RequestParam(defaultValue = "5") Integer limit) {

        List<Map<String, Object>> results = aiSearchService.searchQuestions(query, limit);

        // 记录搜索历史（如果用户已登录）
        if (StpUtil.isLogin()) {
            searchService.saveSearchHistory(StpUtil.getLoginIdAsLong(), query, 1);
        }

        return Result.success(results);
    }

    /**
     * 获取AI回答建议
     */
    @SaCheckLogin
    @GetMapping("/ai/answer-suggestion/{questionId}")
    @Operation(summary = "获取AI回答建议", description = "使用DeepSeek AI获取问题的智能回答建议")
    public Result<String> getAnswerSuggestion(
            @Parameter(description = "问题ID") @PathVariable Long questionId) {

        String suggestion = aiSearchService.getAnswerSuggestion(questionId);
        return Result.success(suggestion);
    }

    /**
     * 获取AI相似问题建议
     */
    @GetMapping("/ai/similar-questions")
    @Operation(summary = "获取AI相似问题推荐", description = "使用DeepSeek AI根据关键词获取相似问题推荐")
    public Result<List<String>> getSimilarQuestions(
            @Parameter(description = "关键词") @RequestParam String keyword,
            @Parameter(description = "返回数量") @RequestParam(defaultValue = "5") Integer limit) {

        List<String> questions = aiSearchService.getSimilarQuestions(keyword, limit);
        return Result.success(questions);
    }

    /**
     * AI分析搜索意图
     */
    @GetMapping("/ai/analyze-intent")
    @Operation(summary = "AI分析搜索意图", description = "使用DeepSeek AI分析用户搜索意图")
    public Result<Map<String, Object>> analyzeSearchIntent(
            @Parameter(description = "搜索查询语句") @RequestParam String query) {

        Map<String, Object> analysis = aiSearchService.analyzeSearchIntent(query);
        return Result.success(analysis);
    }

    /**
     * 搜索问题
     */
    @GetMapping("/questions")
    @Operation(summary = "搜索问题", description = "根据关键词搜索问题")
    public Result<Page<QuestionVO>> searchQuestions(
            @Parameter(description = "关键词") @RequestParam String keyword,
            @Parameter(description = "当前页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "排序方式(1-默认，2-最新，3-最热)") @RequestParam(defaultValue = "1") Integer sort) {

        // 创建分页对象
        Page<Question> page = new Page<>(current, size);

        // 搜索问题
        Page<QuestionVO> result = searchService.searchQuestions(keyword, page, sort);

        return Result.success(result);
    }

    /**
     * 搜索用户
     */
    @GetMapping("/users")
    @Operation(summary = "搜索用户", description = "根据关键词搜索用户")
    public Result<Page<UserVO>> searchUsers(
            @Parameter(description = "关键词") @RequestParam String keyword,
            @Parameter(description = "当前页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size) {

        // 创建分页对象
        Page<User> page = new Page<>(current, size);

        // 搜索用户
        Page<UserVO> result = searchService.searchUsers(keyword, page);

        return Result.success(result);
    }

    /**
     * 获取热门搜索关键词
     */
    @GetMapping("/hot-keywords")
    @Operation(summary = "获取热门搜索关键词", description = "获取热门搜索关键词列表")
    public Result<List<String>> getHotKeywords(
            @Parameter(description = "返回数量") @RequestParam(defaultValue = "10") Integer limit) {

        List<String> hotKeywords = searchService.getHotKeywords(limit);

        return Result.success(hotKeywords);
    }

    /**
     * 保存搜索历史
     */
    @SaCheckLogin
    @PostMapping("/history")
    @Operation(summary = "保存搜索历史", description = "保存用户搜索历史")
    public Result<Boolean> saveSearchHistory(
            @Parameter(description = "搜索关键词") @RequestParam String keyword,
            @Parameter(description = "搜索类型(1-问题, 2-用户)") @RequestParam(defaultValue = "1") Integer type) {

        Long userId = StpUtil.getLoginIdAsLong();
        boolean saved = searchService.saveSearchHistory(userId, keyword, type);

        return Result.success(saved);
    }

    /**
     * 获取用户的搜索历史
     */
    @SaCheckLogin
    @GetMapping("/history")
    @Operation(summary = "获取搜索历史", description = "获取当前用户的搜索历史")
    public Result<List<String>> getSearchHistory(
            @Parameter(description = "返回数量") @RequestParam(defaultValue = "10") Integer limit) {

        Long userId = StpUtil.getLoginIdAsLong();
        List<String> searchHistory = searchService.getUserSearchHistory(userId, limit);

        return Result.success(searchHistory);
    }

    /**
     * 清空搜索历史
     */
    @SaCheckLogin
    @DeleteMapping("/history")
    @Operation(summary = "清空搜索历史", description = "清空当前用户的搜索历史")
    public Result<Boolean> clearSearchHistory() {

        Long userId = StpUtil.getLoginIdAsLong();
        boolean cleared = searchService.clearUserSearchHistory(userId);

        return Result.success(cleared);
    }

    /**
     * 综合搜索
     */
    @GetMapping("/all")
    @Operation(summary = "综合搜索", description = "同时搜索问题和用户")
    public Result<Map<String, Object>> searchAll(
            @Parameter(description = "关键词") @RequestParam String keyword,
            @Parameter(description = "当前页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "5") Integer size) {

        // 同时搜索问题和用户
        Map<String, Object> result = searchService.searchAll(keyword, current, size);

        return Result.success(result);
    }

    /**
     * 搜索相关标签
     */
    @GetMapping("/tags")
    @Operation(summary = "搜索相关标签", description = "根据关键词搜索相关标签")
    public Result<List<String>> searchTags(
            @Parameter(description = "关键词") @RequestParam String keyword,
            @Parameter(description = "返回数量") @RequestParam(defaultValue = "10") Integer limit) {

        List<String> tags = searchService.searchRelatedTags(keyword, limit);

        return Result.success(tags);
    }

    /**
     * 搜索建议
     */
    @GetMapping("/suggest")
    @Operation(summary = "搜索建议", description = "根据输入关键词提供搜索建议")
    public Result<List<String>> getSuggestions(
            @Parameter(description = "关键词") @RequestParam String keyword,
            @Parameter(description = "返回数量") @RequestParam(defaultValue = "5") Integer limit) {

        List<String> suggestions = searchService.getSearchSuggestions(keyword, limit);

        return Result.success(suggestions);
    }

    /**
     * 高级搜索
     */
    @GetMapping("/advanced")
    @Operation(summary = "高级搜索", description = "支持多条件组合的高级搜索")
    public Result<Page<QuestionVO>> advancedSearch(
            @Parameter(description = "关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "标签(多个用逗号分隔)") @RequestParam(required = false) String tags,
            @Parameter(description = "用户ID") @RequestParam(required = false) Long userId,
            @Parameter(description = "开始日期(yyyy-MM-dd)") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期(yyyy-MM-dd)") @RequestParam(required = false) String endDate,
            @Parameter(description = "最小浏览数") @RequestParam(required = false) Integer minViews,
            @Parameter(description = "最小回答数") @RequestParam(required = false) Integer minAnswers,
            @Parameter(description = "当前页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "排序方式(1-默认，2-最新，3-最热，4-最多回答，5-最多点赞)") @RequestParam(defaultValue = "1") Integer sort) {

        // 创建分页对象
        Page<Question> page = new Page<>(current, size);

        // 调用高级搜索服务
        Page<QuestionVO> result = searchService.advancedSearch(keyword, tags, userId, startDate, endDate, minViews, minAnswers, page, sort);

        return Result.success(result);
    }

    /**
     * 清除搜索缓存
     */
    @SaCheckRole("admin")
    @DeleteMapping("/cache")
    @Operation(summary = "清除搜索缓存", description = "清除所有搜索缓存（需要管理员权限）")
    public Result<Boolean> clearSearchCache(
            @Parameter(description = "缓存类型(1-全部, 2-问题搜索, 3-热词, 4-搜索建议)")
            @RequestParam(defaultValue = "1") Integer type) {

        boolean cleared = searchService.clearSearchCache(type);

        return Result.success(cleared);
    }
}
